package com.zhirong.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.zhirong.utils.RequestUtil;
import com.zhirong.common.Result;
import com.zhirong.shiro.PlayUserToken;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
public class HomeController {

    @Autowired
    private WxMaService wxService;

    /**
     * 小程序提交参数code
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestParam("code") String code,
                        @RequestParam(value = "sourceId", required = false) Integer sourceId,
                        HttpServletRequest request) throws WxErrorException {
        if (StringUtils.isBlank(code)) {

        }
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
        String openId = session.getOpenid();
        //1.认证和凭据的token
        PlayUserToken playUserToken = new PlayUserToken(openId, session.getSessionKey(), sourceId);
        String ip = RequestUtil.getIpAdrress(request);
        playUserToken.setHost(ip);
        Subject subject = SecurityUtils.getSubject();
        //2.提交认证和凭据给身份验证系统
        try {
            subject.login(playUserToken);
            return Result.success().data("").msg("登录成功!");
        } catch (AuthenticationException e) {
            log.error("验证登录异常，异常信息:", e);
            return Result.noLogin().msg("用户验证信息错误！");
        } catch (Exception e) {
            log.error("登录异常!", e);
            return Result.error().msg("登陆异常！");
        }
    }
}
